package com.xm.dao.reception_desk;

import com.xm.exception.SqlErrorException;
import com.xm.util.BaseUtil;
import org.intellij.lang.annotations.Language;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 商品规格Dao
 * @author 康文程
 * @date 2024-1-4
 */
public class CommoditySpecificationDao extends BaseUtil {
    /**
     * 根据商品ID查询商品默认规格信息 多个规格用逗号分隔
     * @param commodityId 商品ID
     * @return String 商品规格列表
     */
    public String getSpecificationsByCommodityId(Integer commodityId) {
        @Language("sql")
        String sql = "SELECT GROUP_CONCAT(cs.specification_id) as specification_ids " +
                "FROM commodity AS c " +
                "JOIN commodity_specification AS cs ON c.commodity_id = cs.commodity_id " +
                "JOIN commodity_specification_type AS cst " +
                "ON cs.specification_type_id = cst.specification_type_id " +
                "WHERE cs.is_default = 1 AND c.commodity_id = ?";

        String specificationIds = null;
        ResultSet rs = null;
        try {
            rs = executeQuery(sql, commodityId);
            while (rs.next()){
                specificationIds = rs.getString("specification_ids");
            }
        } catch (SqlErrorException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            close(rs);
        }

        return specificationIds;
    }

    /**
     * 根据规格ID查询规格名称
     * @param specificationId 规格ID
     * @return String 规格名称
     */
    public String getSpecificationNameById(Integer specificationId) {
        @Language("sql")
        String sql = "SELECT specification_name FROM commodity_specification WHERE specification_id = ?";
        String specificationName = null;
        ResultSet rs = null;
        try {
            rs = executeQuery(sql, specificationId);
            while (rs.next()) {
                specificationName = rs.getString("specification_name");
            }
        } catch (SqlErrorException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close(rs);
        }

        return specificationName;
    }
}
